# -*- coding:utf-8 -*-
# 2022/1/19 9:49
# author:xwl
import math

from fastapi import APIRouter, Depends

from backend.app.app.api.api_Xiong.crud.pri_crud import well_cal_get_projid_by_userid
from backend.app.app.api.api_Xiong.crud.pub_crud import get_all_proj_name, get_dvpname_by_projname, \
    get_wellname_by_dvpname, get_year_by_well, get_stimtype_by_well, readdb_and_query_fun, well_cal_save, \
    get_all_proj_name_db
from backend.app.app.api.api_Xiong.models.x_model import projnamelist, dvpnamelist, readdb_and_query_data, \
    well_cal_save_data, well_cal_cal_data
from backend.app.app.api.api_v1.user import verify_token_user
from backend.app.app.api.calculation.evaluation_calculation import wellOprCost, grossSalesIncome, totalTax, staticGains, \
    staticGainsPy, evaluation_calculation5, evaluation_calculation6, evaluation_calculation7, evaluation_calculation8, \
    evaluation_calculation9, evaluation_calculation10

well_cal = APIRouter(prefix="/well_cal", tags=["单井方案评价指标计算"])


@well_cal.post("/get_proj_ID", name="获取现有的Proj_ID")
async def get_proj_ID(userid: str, ver=Depends(verify_token_user)):
    proj_id = well_cal_get_projid_by_userid(userid)
    return {
        "proj_id": proj_id,
        'verify': ver
    }

@well_cal.post("/get_proj_name", name="获取筛选条件1【获取方案名称】")
async def get_proj_name(ver=Depends(verify_token_user)):
    result=get_all_proj_name()
    return {
        "result": result,
        'verify': ver
    }

@well_cal.post("/get_dvpname_by_projname", name="获取筛选条件2【通过方案名称获取开发单元】")
async def get_dvpnamebyprojname(allprojname:projnamelist,ver=Depends(verify_token_user)):
    result=get_dvpname_by_projname(allprojname.Proj_ID)
    return {
        "result": result,
        'verify': ver
    }

@well_cal.post("/get_wellname_by_dvpname", name="获取筛选条件3【通过开发单元找到有的井号】")
async def get_wellnamebydvpname(dvpname:dvpnamelist,ver=Depends(verify_token_user)):
    well_by_rank=get_wellname_by_dvpname(dvpname.DvpUnit_Name)
    year_section=get_year_by_well(well_by_rank)
    stimtype_rank=get_stimtype_by_well(well_by_rank)
    return {
        "well": well_by_rank,
        'year':year_section,
        'stimtype':stimtype_rank,
        'verify': ver
    }

@well_cal.post("/readdb_and_query", name="读库之后查询")
async def readdb_and_query(datas: readdb_and_query_data, ver=Depends(verify_token_user)):
    result1, dvp_oilprocost_result, dvp_oilsalecost_ratio_result=readdb_and_query_fun(datas.DvpUnit_OilStim_PlanProj_Name, datas.Well_Name, datas.StimType_Name, datas.Year)
    return {
        'result1': result1,
        'dvp_oilprocost_result': dvp_oilprocost_result,
        'dvp_oilsalecost_ratio_result': dvp_oilsalecost_ratio_result,
        'verify': ver
    }

@well_cal.post("/save", name="存库")
async def save(datas: well_cal_save_data, ver=Depends(verify_token_user)):
    result = well_cal_save(datas.data, datas.dvp_planproj_polprodcost, datas.dvp_planproj_oilsalecost_ratio, datas.delete)
    return {
        'result':result,
        'verify': ver
    }

@well_cal.post("/calculation", name="计算")
async def well_cal_calculation(datas: well_cal_cal_data, ver=Depends(verify_token_user)):
    result = []
    try:
        for data in datas.cal_data:
            # 1.计算平均增油操作成本
            WellOprCost = wellOprCost(IncreOil=float(data["Stim_IncreOil"]), OilOprCost=float(data["Oil_OprCost"]))

            # 2.计算平均增油毛收入
            GrossSalesIncome = grossSalesIncome(OilPrice=float(data["Oil_Price"]),
                                                OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                IncreOil=float(data["Stim_IncreOil"]))

            # 3.计算平均销售税费
            TotalTax = totalTax(GrossSalesIncome=GrossSalesIncome, TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))

            # 4.平均静态收益（元/井）：StaticGains
            StaticGains = staticGains(StimCost=float(data["Stim_Cost"]), WellOprCost=WellOprCost, TotalTax=TotalTax,
                                      GrossSalesIncome=GrossSalesIncome)

            # 5.平均财务净现值（元/井）：StimNPV
            # ValidPeriod = 123 #有效天  未找到，临时使用
            # 直接计算StaticGainsPy, 后续需要使用
            ValidPeriod = int(data["Stim_ValidPeriod"])
            ValidYears = math.ceil(ValidPeriod / 365)
            ic = float(data["Money_Discount"]) / 100
            StaticGainsPy_by_count = staticGainsPy(IncreOil=float(data["Stim_IncreOil"]), ValidYears=ValidYears,
                                                   OilPrice=float(data["Oil_Price"]),
                                                   OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                   TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]),
                                                   OilOprCost=float(data["Oil_OprCost"]))
            StimNPV = evaluation_calculation5(ValidYears=ValidYears, StaticGainsPy=StaticGainsPy_by_count, ic=ic,
                                              StimCost=float(data["Stim_Cost"]))
            # 6.投资利润率（%）：StimROI
            StimROI = evaluation_calculation6(StaticGains=StaticGains, StimCost=float(data["Stim_Cost"]))
            print("6True")
            # 7.财务净现值率（%）：
            StimNPVR = evaluation_calculation7(StimNPV=StimNPV, StimCost=float(data["Stim_Cost"]))
            print("7True")
            # 8.财务内部收益率（%）：StimFIRR
            # ValidPeriod = data["Stim_ValidPeriod_Average"]
            # ValidYears = math.ceil(ValidPeriod / 365)
            StimFIRR = evaluation_calculation8(ValidYears=ValidYears, StimCost=float(data["Stim_Cost"]),
                                               StaticGainsPy=StaticGainsPy_by_count)
            print("8True")
            # 9.平均经济临界增油量（吨/井）：IncreOilCritical
            # ic = data["Money_Discount"]/100
            IncreOilCritical = evaluation_calculation9(ValidYears=ValidYears, ic=ic, StimCost=float(data["Stim_Cost"]),
                                                       OilPrice=float(data["Oil_Price"]),
                                                       OilOprCost=float(data["Oil_OprCost"]),
                                                       OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                       TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))
            # 10.平均经济临界油价（元/吨）：OilPriceCritical
            increOilPy = float(data["Stim_IncreOil"]) / ValidYears
            OilPriceCritical = evaluation_calculation10(ValidYears=ValidYears, ic=ic, StimCost=float(data["Stim_Cost"]),
                                                        IncreOilPy=increOilPy, OilOprCost=float(data["Oil_OprCost"]),
                                                        OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                        TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))
            # 把所有处理完的数据添加到结果
            temp1 = {
                'User_ID': data['User_ID'],
                'Proj_ID': data['Proj_ID'],
                'DvpUnit_OilStim_PlanProj_Name': data['DvpUnit_OilStim_PlanProj_Name'],
                'DvpUnit_Name': data['DvpUnit_Name'],
                'Well_Name': data['Well_Name'],
                'Year': data['Year'],
                'StimType_Name': data['StimType_Name'],
                'Stim_ValidPeriod': data['Stim_ValidPeriod'],
                'Stim_IncreOil': data['Stim_IncreOil'],
                'Stim_Cost': data['Stim_Cost'],
                'Oil_CommodityRatio': data['Oil_CommodityRatio'],
                'Oil_Price': data['Oil_Price'],
                'Oil_OprCost': data['Oil_OprCost'],
                'OilSale_TotalTaxRatio': data['OilSale_TotalTaxRatio'],
                'Money_Discount': data['Money_Discount'],
                'Remark': data['Remark'],
                "WellOprCost": WellOprCost,
                "TotalTax": TotalTax,
                "GrossSalesIncome": GrossSalesIncome,
                "StaticGains": StaticGains,
                "StimNPV": StimNPV,
                "StimROI": StimROI,
                "StimNPVR": StimNPVR,
                "StimFIRR": StimFIRR,
                "IncreOilCritical": IncreOilCritical,
                "OilPriceCritical": OilPriceCritical
            }
            result.append(temp1)
        return {
            'result': result if result else {},
            'verify': ver
        }
    except Exception as e:
        print(repr(e),e.__traceback__.tb_lineno)


@well_cal.post("/get_oilstim_proj_name", name="获取所有规划方案名称")
async def get_oilstim_proj_name(ver=Depends(verify_token_user)):
    result=get_all_proj_name_db()
    return {
        'result':result,
        'verify': ver
    }